import Router from 'koa-router'
import sseManager from '../../utils/sseManager.js'
import config from '../../config/index.js'

import userRoutes from './user.js'
import RoomController from '../../controllers/RoomController.js'
import roomsRoutes from './rooms.js'
import connectionsRoutes from './connections.js'
import messageRoutes from './message.js'
import metricsRoutes from './metrics.js'

import redis from '../../utils/redis.js'
const DEVICE_PREFIX = 'webrtc:device:'
const ROOM_PREFIX = 'webrtc:room:'
const CALL_PREFIX = 'webrtc:call:'
const CONN_PREFIX = 'webrtc:conn:'

const router = new Router({
    prefix: '/api'
})

router.get('/test', async(ctx) => {
    ctx.body = '耗时请求完成'
})

router.post('/device/bind', (new RoomController).roomCreate)
router.delete('/device/:roomId/:deviceId', async (ctx) => {
    const { roomId, deviceId } = ctx.params
    await redis.srem(DEVICE_PREFIX + roomId, deviceId)
    ctx.body = { success: true }
})
router.get('/device/list', async (ctx) => {
    const deviceKeys = await redis.keys(DEVICE_PREFIX + '*')

    let deviceList = []
    for (const key of deviceKeys) {
        const roomId = key.replace(DEVICE_PREFIX, '')
        const members = await redis.smembers(key)
        for (const device of members) {
            const conn = await redis.hget(ROOM_PREFIX + roomId, device)
            const ex = await redis.exists(CONN_PREFIX + conn)
            deviceList.push({
                roomId: roomId,
                deviceId: device,
                isOnline: ex ? true : false
            })
        }
    }

    ctx.body = {
        errcode: 0,
        errmsg: 'success',
        data: {
            list: deviceList
        }
    }
})

router.get('/health', async(ctx) => {
    ctx.body = { status: 'ok', message: '服务器运行正常' }
})

// SSE连接统计
router.get('/sse/stats', async(ctx) => {
    ctx.body = sseManager.getStats()
})

// 发送消息到所有连接
router.post('/sse/broadcast', async(ctx) => {
    const { message, type = 'broadcast' } = ctx.request.body
    
    if (!message) {
        ctx.status = 400
        ctx.body = { error: '消息内容不能为空' }
        return
    }
    
    const sentCount = sseManager.broadcast({
        type: type,
        message: message,
        timestamp: Date.now()
    })
    
    ctx.body = { 
        success: true, 
        sentCount: sentCount,
        message: `消息已发送到 ${sentCount} 个连接`
    }
})

// 发送消息到指定连接
router.post('/sse/send/:connectionId', async(ctx) => {
    const { connectionId } = ctx.params
    const { message, type = 'direct' } = ctx.request.body
    
    if (!message) {
        ctx.status = 400
        ctx.body = { error: '消息内容不能为空' }
        return
    }
    
    const success = sseManager.sendToConnection(connectionId, {
        type: type,
        message: message,
        timestamp: Date.now()
    })
    
    if (success) {
        ctx.body = { success: true, message: '消息发送成功' }
    } else {
        ctx.status = 404
        ctx.body = { error: '连接不存在或已断开' }
    }
})

router.get('/sse', async (ctx) => {
    console.log('SSE请求到达:', ctx.url, ctx.method)
    
    // 生成连接ID
    const connectionId = `sse_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
    
    // 设置SSE响应头
    ctx.set({
      'Content-Type': 'text/event-stream',
      'Cache-Control': 'no-cache',
      'Connection': 'keep-alive',
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Headers': 'Cache-Control',
      'Access-Control-Allow-Credentials': 'true'
    })
  
    // 不设置ctx.body，直接写入响应流
    ctx.status = 200
    ctx.respond = false

    // 添加到连接管理器
    if (!sseManager.addConnection(connectionId, ctx)) {
      ctx.res.write('data: {"type":"error","message":"连接数已达上限"}\n\n')
      ctx.res.end()
      return
    }
  
    // 发送初始连接确认
    ctx.res.write('data: {"type":"connected","connectionId":"' + connectionId + '","timestamp":' + Date.now() + '}\n\n')
  
    // 处理客户端断开连接
    ctx.req.on('close', () => {
      console.log(`SSE客户端断开连接: ${connectionId}`)
      sseManager.removeConnection(connectionId)
    })
    
    // 处理客户端错误
    ctx.req.on('error', (err) => {
      console.log(`SSE连接错误 ${connectionId}:`, err.message)
      sseManager.removeConnection(connectionId)
    })
})

// 管理界面SSE推送
router.get('/admin/sse', async (ctx) => {
    console.log('管理界面SSE请求到达:', ctx.url, ctx.method)
    
    // 生成连接ID
    const connectionId = `admin_sse_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
    
    // 设置SSE响应头
    ctx.set({
      'Content-Type': 'text/event-stream',
      'Cache-Control': 'no-cache',
      'Connection': 'keep-alive',
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Headers': 'Cache-Control',
      'Access-Control-Allow-Credentials': 'true'
    })
  
    // 不设置ctx.body，直接写入响应流
    ctx.status = 200
    ctx.respond = false

    // 添加到连接管理器
    if (!sseManager.addConnection(connectionId, ctx)) {
      ctx.res.write('data: {"type":"error","message":"连接数已达上限"}\n\n')
      ctx.res.end()
      return
    }
  
    // 发送初始连接确认
    ctx.res.write('data: {"type":"connected","connectionId":"' + connectionId + '","timestamp":' + Date.now() + '}\n\n')
    
    // 启动定时推送
    const pushInterval = setInterval(async () => {
      try {
        // 直接获取Redis数据，避免HTTP请求循环
        const roomKeys = await redis.keys(ROOM_PREFIX + '*')
        const callKeys = await redis.keys(CALL_PREFIX + '*')
        const connKeys = await redis.keys(CONN_PREFIX + '*')
        const deviceKeys = await redis.keys(DEVICE_PREFIX + '*')

        // 获取房间列表
        const rooms = []
        for (const key of roomKeys) {
          const roomId = key.replace(ROOM_PREFIX, '')
          const members = await redis.hgetall(key)
          
          const inCall = await redis.hlen(CALL_PREFIX + roomId)
          for (const device in members) {
            const conn = await redis.hget(ROOM_PREFIX + roomId, device)
            const ex = await redis.exists(CONN_PREFIX + conn)
            rooms.push({
                roomId: roomId,
                deviceId: device,
                connId: members[device] || '',
                isOnline: ex ? true : false,
                status: inCall > 0 ? 'active' : 'idle'
            })
          }
        }

        let deviceList = []
        for (const key of deviceKeys) {
            const roomId = key.replace(DEVICE_PREFIX, '')
            const members = await redis.smembers(key)
            for (const device of members) {
                const conn = await redis.hget(ROOM_PREFIX + roomId, device)
                const ex = await redis.exists(CONN_PREFIX + conn)
                deviceList.push({
                    roomId: roomId,
                    deviceId: device,
                    isOnline: ex ? true : false
                })
            }
        }
        
        const data = {
          type: 'admin_data',
          timestamp: Date.now(),
          metrics: {
            rooms: roomKeys.length,
            calls: callKeys.length,
            connections: connKeys.length,
            websocket: {
              port: config.websocket.port,
              useSSL: config.websocket.useSSL
            }
          },
          rooms: rooms,
          deviceList: deviceList
        }
        
        ctx.res.write('data: ' + JSON.stringify(data) + '\n\n')
      } catch (error) {
        console.error('SSE推送数据失败:', error.message)
        ctx.res.write('data: {"type":"error","message":"数据推送失败"}\n\n')
      }
    }, 5000) // 每3秒推送一次
  
    // 处理客户端断开连接
    ctx.req.on('close', () => {
      console.log(`管理界面SSE客户端断开连接: ${connectionId}`)
      clearInterval(pushInterval)
      sseManager.removeConnection(connectionId)
    })
    
    // 处理客户端错误
    ctx.req.on('error', (err) => {
      console.log(`管理界面SSE连接错误 ${connectionId}:`, err.message)
      clearInterval(pushInterval)
      sseManager.removeConnection(connectionId)
    })
})

router.use(userRoutes.routes())
router.use(roomsRoutes.routes())
router.use(connectionsRoutes.routes())
router.use(messageRoutes.routes())
router.use(metricsRoutes.routes())

export default router